package com.haitonghop.modules.local;


import java.util.ArrayList;

import com.haitonghop.R;
import com.haitonghop.R.id;
import com.haitonghop.R.layout;
import com.haitonghop.controls.DataCachedControl;
import com.haitonghop.controls.IOnFinalPage;
import com.haitonghop.controls.ImagePagerAdapter;
import com.haitonghop.controls.OnSaveComic;
import com.haitonghop.controls.onSocialAction;
import com.haitonghop.controls.onUserCreateTopic;
import com.haitonghop.data.HaiBLMetalData;
import com.haitonghop.data.TamDiemMetalData;
import com.haitonghop.main.ComicBussiness;
import com.haitonghop.main.DisplayUtils;
import com.haitonghop.modules.haivl.HaiVlCommentActivity;
import com.haitonghop.network.APIRequestWorker;
import com.haitonghop.network.Request;
import com.haitonghop.network.RequestListener;
import com.haitonghop.requester.CabVnRequester;
import com.haitonghop.requester.EpicVnRequester;
import com.haitonghop.requester.HaiVLRequester;
import com.haitonghop.requester.TamDiemRequester;
import com.haitonghop.utils.AppSettingParams;
import com.haitonghop.utils.FaceBookUtils;
import com.haitonghop.utils.GlobalData;
import com.haitonghop.utils.Logger;
import com.haitonghop.utils.sqllite.datasource.TopicHaiBLDataSource;
import com.haitonghop.utils.sqllite.datasource.TopicHaiBlData;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TabHost;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.TabWidget;
import android.widget.TextView;
import android.widget.TabHost.TabContentFactory;
import android.widget.Toast;

public class LocalViewTopicActivity extends Activity implements OnItemClickListener, OnItemLongClickListener{
	
	LinearLayout loadingPage = null;
	LinearLayout loadingError = null;
	
	LinearLayout mainContent = null;
	LinearLayout prviewTamDiem = null;
	ListView imageListView = null;
	TextView errorMessageView = null;
	LocalViewTopicRenderAdapter localViewTopicRenderAdapter = null;	
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);		
		
		//Remove notification bar
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.tamdiem_activity_layout);		
		init();
		
		loadingPage = (LinearLayout)findViewById(R.id.loadingpagetamdiem);
		loadingError = (LinearLayout)findViewById(R.id.loadingError);
		errorMessageView  = (TextView)findViewById(R.id.errorMessageView);
		
		errorMessageView.setText("Chưa có chủ đ�? được nào.");
		loadingError.setVisibility(View.INVISIBLE);
		
		mainContent = (LinearLayout)findViewById(R.id.mainContent);
		prviewTamDiem = (LinearLayout)findViewById(R.id.prviewTamDiem);
		imageListView = (ListView)findViewById(R.id.imageListView);
		if(imageListView != null){
			imageListView.setOnItemClickListener(this);
			imageListView.setOnItemLongClickListener(this);
		}
		
		int[] colors = {0, 0xFF000000, 0};
		imageListView.setDivider(new GradientDrawable(Orientation.RIGHT_LEFT, colors));
		imageListView.setDividerHeight(1);
		
		TextView textView = (TextView)findViewById(R.id.titleActivity);
		textView.setText("Chủ đ�?");
		
		Button button = (Button)findViewById(R.id.btnMoreFunctions);
		button.setVisibility(View.GONE);
		
		Button back = (Button) findViewById(R.id.btnBackAcvitity);
		if (back != null) {
			back.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					finish();
				}
			});
		}
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			finish();
			return true;
		}

		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();		
		onStartUp();
	}
	
	@SuppressWarnings("unchecked")
	private void onStartUp(){		
		ArrayList<TopicHaiBlData> topicHaiBlDatas = getComicFromDataBase();
		fillDataIntoAdapter(topicHaiBlDatas);
	}	
	
	ArrayList<TopicHaiBlData> getComicFromDataBase(){
		TopicHaiBLDataSource topicHaiBLDataSource = null;
		try{
			topicHaiBLDataSource = new TopicHaiBLDataSource(this);
			return topicHaiBLDataSource.getAllTopic();
		}catch(Exception e){
			
		} finally {
			if(topicHaiBLDataSource != null){
				topicHaiBLDataSource.close();
			}
		}
		return null;
	}

	
	void init() {
	}
	
	void fillDataIntoAdapter(final ArrayList<TopicHaiBlData> topicHaiBlDatas){
		if(topicHaiBlDatas != null && topicHaiBlDatas.isEmpty()){
			runOnUiThread(new Runnable() {
				
				public void run() {
					prviewTamDiem.setVisibility(View.INVISIBLE);
					loadingPage.setVisibility(View.INVISIBLE);
					imageListView.setVisibility(View.INVISIBLE);
					
					loadingError.setVisibility(View.VISIBLE);
				}
			});
			return;
		}
		if(localViewTopicRenderAdapter == null && topicHaiBlDatas!= null){
			localViewTopicRenderAdapter = new LocalViewTopicRenderAdapter(this, 1, 1, topicHaiBlDatas);
			if(imageListView != null){
				runOnUiThread(new Runnable() {
					
					public void run() {
						prviewTamDiem.setVisibility(View.GONE);
						loadingPage.setVisibility(View.GONE);
						imageListView.setVisibility(View.VISIBLE);
						imageListView.setAdapter(localViewTopicRenderAdapter);
						localViewTopicRenderAdapter.notifyDataSetChanged();
					}
				});				
			}
		}
	}

	public void onItemClick(AdapterView<?> arg0, View arg1, int index, long arg3) {
		if(localViewTopicRenderAdapter != null && index > -1 && index < localViewTopicRenderAdapter.getCount()){
			if(ComicBussiness.getInstance(LocalViewTopicActivity.this).isDeletedComicAsync()){
				Toast.makeText(LocalViewTopicActivity.this, "�?ang xử lý dữ liệu dưới hệ thống, vui lòng đợi trong giây lát.", 2000).show();
			} else {
				TopicHaiBlData blData = localViewTopicRenderAdapter.getItem(index);
				Intent intent = new Intent(getApplication(), LocalViewComicActivity.class);
				
				if(blData != null){
					intent.putExtra("ID", blData.getId());
					intent.putExtra("NAME", blData.getName());
				}
			    startActivity(intent);
			}
		}
		
	}
	
	void refreshAfterDeleted() {
		if (localViewTopicRenderAdapter != null && localViewTopicRenderAdapter.isEmpty()) {
			runOnUiThread(new Runnable() {

				public void run() {
					prviewTamDiem.setVisibility(View.INVISIBLE);
					loadingPage.setVisibility(View.INVISIBLE);
					imageListView.setVisibility(View.INVISIBLE);

					loadingError.setVisibility(View.VISIBLE);
				}
			});
		}
	}
	
	AlertDialog actionChoice = null;
	void showTopicListsDialogChoice(final TopicHaiBlData data,final int index) {
		if(data == null) return;
		
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Chỉnh sửa chủ đ�?");

		final String[] choiceList = new String[]{
				"Xóa","Sửa tên"
		};
		int selected = -1;
		builder.setSingleChoiceItems(choiceList, selected, new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				actionChoice.dismiss();
				if (which == 0) {
					// deleted
					DisplayUtils.openConfirmDialog("Xóa chủ đ�?", "Bạn thật sự muốn xóa chủ đ�? \"" + data.getName() + "\"?", LocalViewTopicActivity.this, new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {
							boolean isDone = ComicBussiness.getInstance(LocalViewTopicActivity.this).doDeletedTopic(LocalViewTopicActivity.this, data);
							if(isDone){
								Toast.makeText(LocalViewTopicActivity.this, "Xóa chủ đ�? "+data.getName()+" thành công.", 1000).show();
							} else {
								Toast.makeText(LocalViewTopicActivity.this, "Xóa chủ đ�? "+data.getName()+" lỗi.", 1000).show();
							}
							localViewTopicRenderAdapter.remove(data);
							localViewTopicRenderAdapter.notifyDataSetChanged();
							refreshAfterDeleted();
						}
					}, null);
				} else if (which == 1) {
					// edit name
					DisplayUtils.openDialogEnterNameTopic("�?ổi tên", "Bạn muốn đổi tên chủ đ�? \"" + data.getName() + "\" thành :", LocalViewTopicActivity.this, new onUserCreateTopic() {

						public void onCreate(String name) {
							if(!"".equals(name)){
								boolean isDone = ComicBussiness.getInstance(LocalViewTopicActivity.this).changeTopicName(LocalViewTopicActivity.this, data, name);
								if(isDone){
									Toast.makeText(LocalViewTopicActivity.this, "�?ổi tên chủ đ�? "+data.getName()+" thành "+name+" hoàn tất.", 1000).show();
								} else {
									Toast.makeText(LocalViewTopicActivity.this, "�?ổi tên chủ đ�? "+data.getName()+" lỗi.", 1000).show();
								}
								localViewTopicRenderAdapter.getItem(index).setName(name);
								localViewTopicRenderAdapter.notifyDataSetChanged();
							} else {
								Toast.makeText(LocalViewTopicActivity.this, "Lỗi, vui lòng đặt tên chủ đ�?", 1000).show();
							}							
						}

						public void onCancel() {
							// TODO Auto-generated method stub

						}
					});
				}
			}
		});

		builder.setNegativeButton("�?óng", null);
		actionChoice = builder.create();
		actionChoice.show();
	}
	
	public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int index, long arg3) {
		if(localViewTopicRenderAdapter != null && index > -1 && index < localViewTopicRenderAdapter.getCount()){
			TopicHaiBlData data = localViewTopicRenderAdapter.getItem(index);
			showTopicListsDialogChoice(data,index);
		}		
		return true;
	}
}
